<template>
  <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="visible"
    lock-scroll class="wpwork-dialog wpwork-dialog_center" width="600px">
    <span slot="title" class="custom-dialog-title">
      <span class="title-line"></span>
      <span class="title-text">{{ !dataForm.id ? '新增作业资源' : '修改作业资源' }}</span>
    </span>

    <el-form ref="dataForm" v-loading="formLoading" :model="dataForm" :rules="dataRule"
      label-width="100px" class="menuForm">
      <h3>基础信息</h3>
      <wpwork-form-tip-item label="类别" prop="type">
        <el-select v-model="dataForm.type" @change="selectChange" placeholder="请选择类别" clearable
          filterable>
          <el-option v-for="(item,key) in typeList" :key="key" :label="item.fullName"
            :value="item.fullName">
          </el-option>
        </el-select>
      </wpwork-form-tip-item>
      <wpwork-form-tip-item label="名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="输入名称" />
      </wpwork-form-tip-item>
      <wpwork-form-tip-item label="位置坐标" prop="location">
        <span :style="dataForm.location ? 'color: #5AC725':'color: #929292'">{{
            dataForm.location ? "已标注" : "未标注"
          }}</span>
        <a @click="openMap()" class="icon-link">点击这里标注</a>
        <a @click="openWindow()" class="icon-link">手动填写经纬度</a>
        <a @click="clearlocation()" class="icon-link">清除标注</a>
      </wpwork-form-tip-item>
      <wpwork-form-tip-item label="地图显示" prop="mapShow">
        <el-switch v-model="dataForm.mapShow" :active-value="1" :inactive-value="0" />
        <span style="margin-left: 10px;">是否显示在地图上</span>
      </wpwork-form-tip-item>
      <wpwork-form-tip-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="输入备注" />
      </wpwork-form-tip-item>
      <el-collapse class="collapse">
        <el-collapse-item title="配置更多基础信息" name="1">
          <wpwork-form-tip-item label="地理位置">
            <el-input v-model="dataForm.locationdesc" placeholder="输入地理位置描述" />
          </wpwork-form-tip-item>
          <wpwork-form-tip-item label="NFC标签">
            <el-input v-model="dataForm.nfc" placeholder="输入NFC标签" />
          </wpwork-form-tip-item>
          <wpwork-form-tip-item label="WIFI识别码">
            <el-input v-model="dataForm.wifi" placeholder="输入WIFI识别码" />
          </wpwork-form-tip-item>
          <wpwork-form-tip-item label="图片">
            <div class="img-list">
              <single-img v-model="dataForm.picurl1" tip="图片" />
              <single-img v-model="dataForm.picurl2" tip="图片" />
              <single-img v-model="dataForm.picurl3" tip="图片" />
            </div>
          </wpwork-form-tip-item>
        </el-collapse-item>
        <el-collapse-item title="自定义扩展信息" name="2">
          <wpwork-form-tip-item label="是否通过数据审核"
            tip-label="当前作业资源的数据由终端数据采集获得时，需通过审核后勾选此项才能正常使用，仅修改资源显示" prop="mapShow">
            <el-switch v-model="dataForm.dataReview" :active-value="1" :inactive-value="0" />
          </wpwork-form-tip-item>
        </el-collapse-item>
      </el-collapse>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('common.cancelButton') }}</el-button>
      <el-button type="primary" :loading="btnLoading" @click="dataFormSubmit()">
        {{ $t('common.confirmButton') }}</el-button>
    </span>
    <el-dialog title="手动填写经纬度" :modal="false" :visible.sync="locationVisible"
      style="margin-left: 33%;margin-top: 11%;">
      <el-form :model="dataForm" class="menuForm" label-width="100px">
        <wpwork-form-tip-item label="经纬度"
          tip-label="说明：单个定位点，填写一对数据；多边形的定位点，输入多个成对数据，用逗号分隔，目前手动输入只支持单点和多边形">
          <el-input v-model="dataForm.location"></el-input>
        </wpwork-form-tip-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click="closWindow(false)">取 消</el-button> -->
        <el-button type="primary" @click="closWindow(true)">关 闭</el-button>
      </div>
    </el-dialog>
    <!--    <el-dialog title="地图标注" :modal="false" :visible.sync="locationVisible2"-->
    <!--      style="margin-left: 12%; margin-top: 5%;" class="ditudialog" @opened="initMap"-->
    <!--      @close="clearMap">-->
    <!--      &lt;!&ndash; 地图容器 &ndash;&gt;-->
    <!--      <div id="amap-container" style="width: 100%; height:65vh;"></div>-->

    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="locationVisible2 = false">取 消</el-button>-->
    <!--        <el-button type="primary" @click="confirmLocation">确 定</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
    <wpworkMap :type="mapType" :initialCoordinates="initialCoordinates" v-if="locationVisible2"
      @close="mapRtn" />
  </el-dialog>
</template>

<script>
import iconBox from "@/components/wpwork-iconBox";
import clipboard from "@/utils/clipboard";
import request from "@/utils/request";
import wpworkMap from "@/components/wpworkMap/index.vue";
import { List } from "@/api/onlineDev/schedule";
import singleImg from '@/components/Upload/SingleImg'

export default {
  components: { iconBox, wpworkMap, singleImg },
  data() {
    return {
      initialCoordinates: [],
      mapType: "point",
      map: null,         // 地图实例
      marker: null,      // 标记点
      rectangle: null,   // 矩形框选
      currentLocation: null, // 临时存储选中的位置或范围
      locationVisible2: false,
      locationVisible: false,
      typeList: [
        { id: 1, fullName: "自助标点/考勤点" },
        { id: 3, fullName: "设备" },
        { id: 4, fullName: "设施" },
        { id: 5, fullName: "围栏" },
        { id: 6, fullName: "网格" }
      ],
      visible: false,
      dataForm: {
        id: "",
        name: "",
        type: "",
        location: "",
        mapShow: 0,
        remark: "",
        locationdesc: "",
        nfc: "",
        wifi: "",
        picurl1: "",
        picurl2: "",
        picurl3: "",
        dataReview: "",
      },
      dataRule: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        type: [{ required: true, message: "类别不能为空", trigger: "blur" }],
        location: [
          {
            validator: (rule, value, callback) => {
              // 获取当前表单的 type 值
              const type = this.dataForm.type;

              // 如果 type 是 '围栏' 或 '网格'，则 location 必填
              if (type == "围栏" || type == "网格") { // 推荐用 id 而不是文字
                if (!value) {
                  return callback(new Error("位置坐标不能为空"));
                }
              }
              // 否则不校验（可为空）
              callback();
            },
            trigger: 'blur' // 或 'change'
          }
        ]
      },
      formLoading: false,
      iconBoxVisible: false,
      btnLoading: false,
      selfUrl: ""
    };
  },
  methods: {

    selectChange(value) {
      console.log("🚀 ~ :168 ~ selectChange ~ value:", value)
      this.dataForm.location = null;
      this.initialCoordinates = null;
      if (value == "自助标点/考勤点" || value == "设备" || value == "设施") {
        this.mapType = "point"
      } else {
        this.mapType = "polygon"
      }
    },
    mapRtn(rtn) {
      console.log("🚀 ~ :181 ~ mapRtn ~ rtn:", rtn)
      this.locationVisible2 = false
      if (rtn) {
        this.dataForm.location = rtn;
      }
    },
    // 初始化地图
    initMap() {
      if (typeof AMap === 'undefined') {
        this.$message.error('高德地图 SDK 加载失败');
        return;
      }

      if (this.map) return;

      // 默认中心：武汉
      let center = [114.3052, 30.5928];

      // 初始化地图
      this.map = new AMap.Map('amap-container', {
        zoom: 12,
        center: center,
        viewMode: '2D'
      });

      // 添加 ControlBar
      AMap.plugin(['AMap.ControlBar'], () => {
        this.map.addControl(new AMap.ControlBar({
          showZoomBar: true,
          showControlButton: true
        }));
      });

      // 点击选点
      this.map.on('click', (e) => {
        const lnglat = e.lnglat;
        this.selectPoint(lnglat);
      });

      // 启用框选
      this.enableRectSelect();

      // ✅ 打开时回显已有的位置
      this.showExistingLocation();
    },
    showExistingLocation() {
      const location = this.dataForm.location;
      if (!location) return;

      if (location.type === 'point') {
        // 显示点
        this.marker = new AMap.Marker({
          position: [location.lng, location.lat],
          map: this.map
        });
        // 聚焦到该点
        this.map.setCenter([location.lng, location.lat]);
      } else if (location.type === 'rectangle') {
        // 显示矩形框
        const bounds = new AMap.Bounds(
          new AMap.LngLat(location.sw.lng, location.sw.lat), // 西南角
          new AMap.LngLat(location.ne.lng, location.ne.lat)  // 东北角
        );

        this.rectangle = new AMap.Rectangle({
          bounds: bounds,
          map: this.map,
          strokeColor: '#FF33FF',
          strokeWeight: 6,
          strokeOpacity: 0.8,
          fillColor: '#1791fc',
          fillOpacity: 0.3
        });

        // 聚焦到该区域
        this.map.setFitView([this.rectangle]);
      }
    },

    // 清除所有已有的标记和矩形
    clearAllOverlays() {
      if (this.marker) {
        this.map.remove(this.marker);
        this.marker = null;
      }
      if (this.rectangle) {
        this.map.remove(this.rectangle);
        this.rectangle = null;
      }
      this.currentLocation = null;
    },

    // 单点选择
    selectPoint(lnglat) {
      // ✅ 清除之前的点或框选
      this.clearAllOverlays();

      // 创建新标记
      this.marker = new AMap.Marker({
        position: lnglat,
        map: this.map
      });

      // 聚焦
      this.map.setCenter(lnglat);

      // 保存为单点
      this.currentLocation = {
        type: 'point',
        lng: lnglat.lng,
        lat: lnglat.lat
      };
    },

    // 启用矩形框选
    enableRectSelect() {
      // 动态加载 MouseTool 插件
      AMap.plugin('AMap.MouseTool', () => {
        // 每次都创建新的 MouseTool 实例
        const mouseTool = new AMap.MouseTool(this.map);

        // 监听 draw 事件（每次框选都会触发）
        AMap.event.addListener(mouseTool, 'draw', (e) => {
          // ✅ 清除之前的点或区域
          this.clearAllOverlays();

          const bounds = e.obj.getBounds();
          const ne = bounds.getNorthEast();
          const sw = bounds.getSouthWest();

          // 保留当前矩形（用于删除）
          this.rectangle = e.obj;
          this.map.add(this.rectangle); // 确保添加到地图

          // 存储数据
          this.currentLocation = {
            type: 'rectangle',
            ne: { lng: ne.lng, lat: ne.lat },
            sw: { lng: sw.lng, lat: sw.lat }
          };

          // 🚫 不要 close()，允许用户再次框选覆盖
          // mouseTool.close(); ❌ 删除这行
        });

        // 🔧 开启矩形绘制模式
        mouseTool.rectangle();

        // ✅ 把 mouseTool 存到实例上，方便后续管理（可选）
        this.mouseTool = mouseTool;
      });
    },

    // 确认选择
    confirmLocation() {
      if (!this.currentLocation) {
        this.$message.warning('请先选择一个位置或区域');
        return;
      }

      // 写入 dataForm
      this.dataForm.location = this.currentLocation;
      console.log("🚀 ~ :281 ~ confirmLocation ~ this.dataForm.locationJSON:", this.dataForm.locationJSON)
      console.log("🚀 ~ :279 ~ confirmLocation ~ this.dataForm.location:", this.dataForm.location)
      this.$message.success('位置已保存');
      this.locationVisible2 = false;
    },

    // 清理地图资源（关闭 dialog 时调用）
    clearMap() {
      if (this.marker) {
        this.map.remove(this.marker);
        this.marker = null;
      }
      if (this.rectangle) {
        this.map.remove(this.rectangle);
        this.rectangle = null;
      }

      // ✅ 关闭鼠标工具
      if (this.mouseTool) {
        this.mouseTool.close(); // 关闭绘制
        this.mouseTool = null;
      }

      // 销毁地图
      if (this.map) {
        this.map.off('click'); // 解绑点击事件
        this.map.destroy();
        this.map = null;
      }

      this.currentLocation = null;
    },
    clearlocation() {
      this.dataForm.location = ""
    },
    openMap() {
      console.log("🚀 ~ :381 ~ openMap ~this.dataForm.location:", this.dataForm.location)
      this.initialCoordinates = this.dataForm.location;
      if (this.initialCoordinates && this.initialCoordinates.length === 2) {
        this.mapType = "point"
      } else if ((this.initialCoordinates && this.initialCoordinates.length != 2)) {
        this.mapType = "polygon"
      }
      console.log("🚀 ~ :381 ~ openMap ~ this.mapType:", this.mapType)
      console.log("🚀 ~ :375 ~ openMap ~ this.initialCoordinates:", this.initialCoordinates)
      this.locationVisible2 = true;
    },
    openWindow() {
      this.locationVisible = true;
      this.dataForm.location = this.dataForm.location ? Array.isArray(this.dataForm.location) ? JSON.stringify(this.dataForm.location) : this.dataForm.location : ''
      console.log("🚀 ~ :145 ~ openWindow ~ this.locationVisible:", this.locationVisible)
    },
    closWindow(val) {
      console.log("🚀 ~ :325 ~ closWindow ~ val:", val)
      this.locationVisible = false;
      this.dataForm.location = this.dataForm.location ? JSON.parse(this.dataForm.location) : "";
    },
    closeDataForm() {
      this.dataForm = {
        id: "",
        name: "",
        type: "",
        location: "",
        mapShow: 0,
        remark: "",
        locationdesc: "",
        nfc: "",
        wifi: "",
        picurl1: "",
        picurl2: "",
        picurl3: "",
        dataReview: "",
      }
    },
    init(id) {
      this.closeDataForm();
      if (!id) {
        this.mapType = "point"
      }
      console.log("🚀 ~ :107 ~ init ~ id:", id)
      this.dataForm.id = id || "";
      this.selfUrl = "";
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.formLoading = true;
          request({
            url: `/api/example/WorkResources/getOne`,
            method: "post",
            params: { id: this.dataForm.id }
          }).then((res) => {
            console.log("🚀 ~ :168 ~ init ~ res:", res.data)
            this.dataForm = res.data;
            this.dataForm.location = JSON.parse(this.dataForm.location)
            console.log("🚀 ~ :391 ~ init ~ this.dataForm:", this.dataForm)
            this.$nextTick(() => {
              this.formLoading = false;
            });
          })


        } else {
        }
      });
    },
    openIconBox() {
      this.iconBoxVisible = true;
    },
    dataFormSubmit() {
      console.log("🚀 ~ :140 ~ dataFormSubmit ~ this.dataForm:", this.dataForm)
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.btnLoading = true;
          const query = {
            ...this.dataForm,
            location: JSON.stringify(this.dataForm.location)
          };
          console.log("🚀 ~ :203 ~ dataFormSubmit ~ query:", query)
          if (this.dataForm.id) {
            request({
              url: `/api/example/WorkResources/update`,
              method: "post",
              data: query
            }).then(res => {
              console.log("🚀 ~ :210 ~ dataFormSubmit ~ res:", res)
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refreshDataList");
                }
              });
            }).catch(() => {
              this.btnLoading = false;
            });
          } else {
            request({
              url: `/api/example/WorkResources/add`,
              method: "post",
              data: query
            }).then(res => {
              console.log("🚀 ~ :210 ~ dataFormSubmit ~ res:", res)
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.btnLoading = false;
                  this.$emit("refreshDataList");
                }
              });
            }).catch(() => {
              this.btnLoading = false;
            });
          }

        }
      });
    },
    choiceIcon(value) {
      this.dataForm.icon = value;
    },
    getSelfUrl(enCode) {
      if (!enCode) return (this.selfUrl = "");
      this.selfUrl = `${window.location.origin}/wpwork_APP_${enCode}`;
    },
    handleCopy(text, event) {
      if (text) clipboard(text, event);
    },
  }
};
</script>
<style lang="scss" scoped>
.img-list {
  display: flex;

  > .singleImg-container {
    margin-right: 20px;

    :last-child {
      margin-right: 0;
    }
  }
}

.icon-link {
  color: #409eff;
  margin-left: 10px;
}

.collapse {
  ::v-deep .el-collapse-item__header {
    font-size: 1rem;
    font-weight: 600;
  }
}

.ditudialog {
  ::v-deep .el-dialog {
    width: 80vw;
    height: 80vh;
  }
}

::v-deep .el-dialog__header {
  background-color: #f8f8f8;
  border-bottom: none;
}

.custom-dialog-title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0;
  padding: 0;
}

.title-line {
  width: 4px;
  height: 16px;
  background: linear-gradient(to bottom, #3f72e7, #84b0fc);
  margin-right: 10px;
  border-radius: 2px;
}

.title-text {
  font-weight: 900;
  margin: 0;
  padding: 0;
}
</style>